/**
 * @copyright 2017 sinping.com 北京芯平科技股份有限公司. All rights reserved.
 * 本内容仅限于北京芯平科技股份有限公司内部传阅，禁止外泄以及用于其他的商业目的.
 */
package com.sinping.qh.api.auth;

import com.baomidou.mybatisplus.plugins.Page;
 import com.sinping.qh.api.support.*;
import com.sinping.qh.domain.auth.UserLog;
import com.sinping.qh.dto.auth.UserLogDTO;
import com.sinping.qh.service.auth.IUserLogService;
import com.sinping.qh.utils.ip.IPUtils;
import com.sinping.qh.utils.mapper.BeanMapper;
import com.sinping.qh.utils.mapper.JsonMapper;
import com.sinping.qh.utils.misc.IdGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 行为日志管理
 *
 * @author xuerunjia
 * @create 2017/12/21
 */
@Api(value = "Admin行为日志管理",description = "Admin行为日志管理API")
@RestController
@RequestMapping(value = Const.BASE_URI + "log/operation",name =  "行为日志管理")
public class UserLogPoint {

    private static final Logger log = LoggerFactory.getLogger(UserLogPoint.class);

    @Autowired
    private IUserLogService userLogService;


    @ApiOperation(value = "新增行为日志", consumes = MediaTypes.TEXT_HTML)
    @RequestMapping(name = "新增行为日志", method = RequestMethod.POST)
    public ResDto insertLog(HttpServletRequest request, @ApiParam(name = "msg", value = "{\"user_id\":\"1234\",\"nickname\":\"李四的nickname\",\"user_name\":\"李四\",\"type\":2,\"operation\":\"新增用户 张三\"}") @RequestParam(required = true) String msg) {
        log.debug("新增行为日志信息，参数为：{}。", msg);
        UserLogDTO userLogDTO = JsonMapper.defaultMapper().fromJson(msg, UserLogDTO.class);
        if (userLogDTO == null || StringUtils.isEmpty(userLogDTO.getUserId())) {
            ResDto resDto = new ResDto(ConstEum.PARAM_ERROR);
            resDto.setMsg("msg.param.format.error");
            return resDto;
        }
        boolean isSuccess = false;
        try {
            userLogDTO.setId(IdGenerator.uuid2());
            userLogDTO.setCreateTime(new Date());
            userLogDTO.setLoginIp(IPUtils.getIpAddr(request));

            UserLog userLog = BeanMapper.map(userLogDTO, UserLog.class);
            isSuccess = userLogService.insert(userLog);
        } catch (DataIntegrityViolationException e) {
            log.error(e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            log.error("新增日志失败", e);
            return new ResDto(ConstEum.SERVER_ERROR);
        }
        if (isSuccess) {
            return new ResDto(ConstEum.SUCCESS);
        } else {
            return new ResDto(ConstEum.SERVER_ERROR);
        }
    }


    @ApiOperation(value = "行为日志信息列表")
    @RequestMapping(name = "行为日志信息列表", method = RequestMethod.GET)
    public ResDto logList(@ApiParam(name = "msg", value = "{\"page_size\":\"10\",\"page_current\":\"1\",\"order_column\":null, \"order_by\":null, \"condition\":{\"`key`\":\"value\"}}") @RequestParam(required = true) String msg) {
        log.debug("行为日志信息列表，参数为：{}。", msg);
        FrontPage<UserLog> paramPage = JsonMapper.defaultMapper().fromJson(msg, FrontPage.class);
        if (paramPage == null) {
            ResDto resDto = new ResDto(ConstEum.PARAM_ERROR);
            resDto.setMsg("msg.param.format.error");
            return resDto;
        }
        try {
            Page<UserLog> userLogPage = this.userLogService.selectPageData(paramPage);
            FrontPage resultPage = new FrontPage(userLogPage);
            resultPage.setRecords(BeanMapper.mapList(userLogPage.getRecords(), UserLogDTO.class));
            String data = JsonMapper.defaultMapper().toJson(resultPage);
            ResDto resDto = new ResDto(ConstEum.SUCCESS);
            resDto.setDatas(data);
            log.debug("行为信息日志信息列表加载成功，数据：{}", data);
            return resDto;
        }catch (DataIntegrityViolationException e) {
            log.error(e.getMessage(), e);
            throw e;
        } catch (Exception e) {
            log.error("日志列表信息加载失败", e);
            return new ResDto(ConstEum.SERVER_ERROR);
        }
    }


}
